//
//  YNUserGroup.m
//  Messenger
//
//  Created by OC on 15/1/19.
//  Copyright (c) 2015年 李健. All rights reserved.
//
//  群/讨论组实体类 groupType:1 群  groupType:2 讨论组
//

#import "YNContactGroup.h"
#import "FMDatabase.h"
#import "FMDatabaseQueue.h"
#import "FMDatabaseAdditions.h"
#import "YNIMTool.h"
#import "YNIMFrameworkMacro.h"

@implementation YNContactGroup

-(void)setValue:(id)value forUndefinedKey:(NSString *)key{
    if (!value) {
        if ([key isEqualToString:@"maxUsers"]) {
            self.maxUsers=0;
        }
    }
}

+ (NSString *)groupName
{
    return @"groupName";
}

+ (NSString *)createUser
{
    return @"createUser";
}

+ (NSString *)createTime
{
    return @"createTime";
}

+ (NSString *)naturalName
{
    return @"naturalName";
}

+ (NSString *)subject
{
    return @"subject";
}

+ (NSString *)maxUsers
{
    return @"maxUsers";
}

+ (NSString*)groupType
{
    return @"groupType";
}

+ (NSString *)desc
{
    return @"desc";
}

+ (NSString *)tableName
{
    return @"GroupTable";
}

+ (NSString *)tableGroupName
{
    return @"GroupRelations";
}

- (NSArray *)insertParamOfGroup
{
    return @[[YNIMTool nilFilter:self.groupName],
             [NSNumber numberWithInteger:self.groupType],
             [YNIMTool nilFilter:self.createUser],
             [YNIMTool nilFilter:self.createTime],
             [YNIMTool nilFilter:self.naturalName],
             [YNIMTool nilFilter:self.subject],
             [NSNumber numberWithInt:self.maxUsers],
             [YNIMTool nilFilter:self.desc]];
}

- (NSArray *)updateParamOfGroup
{
    return @[[YNIMTool nilFilter:self.createUser],
             [NSNumber numberWithInteger:self.groupType],
             [YNIMTool nilFilter:self.createTime],
             [YNIMTool nilFilter:self.naturalName],
             [YNIMTool nilFilter:self.subject],
             [NSNumber numberWithInt:self.maxUsers],
             [YNIMTool nilFilter:self.desc],
             [YNIMTool nilFilter:self.groupName]];
}

//创建群或讨论组表
+ (BOOL)createDatabase:(FMDatabase *)db
{
    if ([db tableExists:[YNContactGroup tableName]])
    {
        return YES;
    }
    NSString *createGroupSql = [NSString stringWithFormat:@"%@%@(%@ varchar(36) NOT NULL PRIMARY KEY UNIQUE, %@ varchar(36), %@ varchar(30), %@ varchar(36),%@ varchar(100),%@ INTEGER,%@ INTEGER,%@ varchar(100))",CREATE_TABLE,
                                [YNContactGroup tableName],
                                [YNContactGroup groupName],
                                [YNContactGroup createUser],
                                [YNContactGroup createTime],
                                [YNContactGroup naturalName],
                                [YNContactGroup subject],
                                [YNContactGroup maxUsers],
                                [YNContactGroup groupType],
                                [YNContactGroup desc]];
    
    BOOL result = [db executeUpdate:createGroupSql];
    
    return result;
}
//插入群或讨论组
- (BOOL)insertGroupDatabase:(FMDatabase *)db
{
    
    NSString *fieldString = [NSString stringWithFormat:@"%@,%@,%@,%@,%@,%@,%@,%@",
                             [YNContactGroup groupName],
                             [YNContactGroup groupType],
                             [YNContactGroup createUser],
                             [YNContactGroup createTime],
                             [YNContactGroup naturalName],
                             [YNContactGroup subject],
                             [YNContactGroup maxUsers],
                             [YNContactGroup desc]];
    
    
    NSString *insertGroupSql = [NSString stringWithFormat:@"%@%@ (%@) VALUES (?,?,?,?,?,?,?,?)",INSERT_TABLE,[YNContactGroup tableName],fieldString];
    
    BOOL result = [db executeUpdate:insertGroupSql withArgumentsInArray:[self insertParamOfGroup]];
    
    return result;
}

//根据gruoupName查询群或讨论组信息
+ (NSArray *)queryContactGroupByGroupName:(NSString *)groupName database:(FMDatabase *)db
{
    NSString *queryGroupSql = [NSString stringWithFormat:@"SELECT * FROM %@ WHERE %@ = ?",
                               [YNContactGroup tableName],
                               [YNContactGroup groupName]];
    NSMutableArray *groupArray = [NSMutableArray array];
    
    FMResultSet *rs = [db executeQuery:queryGroupSql,groupName];
    
    while ([rs next])
    {
        YNContactGroup *group = [[YNContactGroup alloc] init];
        if (![YNIMTool isEmptyDictionary:[rs resultDictionary]]) {
             [group setValuesForKeysWithDictionary:[rs resultDictionary]];
        }
       
        
        [groupArray addObject:group];
    }
    
    return groupArray;
}

//查询全部群或讨论组信息
+ (NSArray *)queryContactGroupWithGroupType:(CurrenChatObjType)groupType database:(FMDatabase *)db
{
    NSString *userId = [YNIMmanager sharedInstance].userImId;
    
    NSString *queryGroupSql = [NSString stringWithFormat:@"SELECT a.* ,b.role FROM %@ a join %@ b on a.groupName = b.groupName and a.groupType = %@ where b.userNo = '%@'",
                               [YNContactGroup tableName],[YNContactGroup tableGroupName],[NSNumber numberWithInteger:groupType],userId];
    NSMutableArray *groupArray = [NSMutableArray array];
    
    FMResultSet *rs = [db executeQuery:queryGroupSql];
    
    while ([rs next])
    {
        YNContactGroup *group = [[YNContactGroup alloc] init];
        if (![YNIMTool isEmptyDictionary:[rs resultDictionary]]) {
             [group setValuesForKeysWithDictionary:[rs resultDictionary]];
        }
       
        [groupArray addObject:group];
    }
    
    return groupArray;
}

//根据gruoupName更新群或讨论组信息
- (BOOL)updateGroupDatabase:(FMDatabase *)db
{
    NSString *updateGroupSql = [NSString stringWithFormat:@"UPDATE %@ SET %@ = ?, %@ = ?, %@ = ?, %@ = ?, %@ = ?, %@ = ?, %@ = ? WHERE %@ = ?",
                                [YNContactGroup tableName],
                                [YNContactGroup createUser],
                                [YNContactGroup groupType],
                                [YNContactGroup createTime],
                                [YNContactGroup naturalName],
                                [YNContactGroup subject],
                                [YNContactGroup maxUsers],
                                [YNContactGroup desc],
                                [YNContactGroup groupName]];
    
    BOOL result = [db executeUpdate:updateGroupSql withArgumentsInArray:[self updateParamOfGroup]];
    
    return result;
}


//根据关键字查询Group
+ (NSArray *)queryGroupByKeywords:(NSString *)keyWords groupType:(CurrenChatObjType)groupType database:(FMDatabase *)db
{
    NSString *queryGroupByKeywords = [NSString stringWithFormat:@"SELECT * FROM %@ WHERE %@ = %@ AND %@ like '%%%@%%'escape '/'",[YNContactGroup tableName],[YNContactGroup groupType],[NSNumber numberWithInteger:groupType],(groupType == CurrenChatObjType_group || groupType == CurrenChatObjType_projectTeam) ? [YNContactGroup naturalName] : [YNContactGroup subject],keyWords];
    
    FMResultSet *rs = [db executeQuery:queryGroupByKeywords];
    
    NSMutableArray *tempGroupArray = [NSMutableArray array];
    
    while ([rs next])
    {
        YNContactGroup *group = [[YNContactGroup alloc] init];
        if (![YNIMTool isEmptyDictionary:[rs resultDictionary]]) {
            [group setValuesForKeysWithDictionary:[rs resultDictionary]];
        }
        
        [tempGroupArray addObject:group];
    }
    
    [rs close];
    
    return tempGroupArray;
    
}

// 判断群组/讨论组是否存在
- (BOOL)isContactGroupExistInDatabase:(FMDatabase *)db
{
    NSArray *groupArray = [YNContactGroup queryContactGroupByGroupName:self.groupName database:db];
    
    if (groupArray.count > 0)
    {
        return YES;
    }
    
    return NO;
}

//删除表中所有数据
+ (BOOL)deleteAllDataWithGroupType:(CurrenChatObjType)groupType database:(FMDatabase *)db
{
    NSString *deleteAllContactGroupSql = [NSString stringWithFormat:@"DELETE FROM %@ WHERE %@ = %@",[YNContactGroup tableName],[YNContactGroup groupType],[NSNumber numberWithInteger:groupType]];
    //删除自增字段数据
    NSString *deleteAutoFieldSql = [NSString stringWithFormat:@"UPDATE sqlite_sequence SET seq = 0 WHERE name='%@'",[YNContactGroup tableName]];
    
    BOOL result = [db executeUpdate:deleteAllContactGroupSql];
    
    if (result)
    {
        result = [db executeUpdate:deleteAutoFieldSql];
    }
    
    return result;
}


//根据groupName删除数据
- (BOOL)deleteWithGroupDatabase:(FMDatabase *)db
{
    NSString *deleteContactGroupSql = [NSString stringWithFormat:@"DELETE FROM %@ WHERE %@ = ?",[YNContactGroup tableName],[YNContactGroup groupName]];
    
    BOOL result = [db executeUpdate:deleteContactGroupSql,self.groupName];
    
    return result;
}
@end
